package com.FOD.fragments;

import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;
import com.FOD.clases.R;
import com.FOD.clases.globalFunctions;
import com.FOD.entities.EmpleadoHorario;
import com.FOD.entities.User;
import com.FOD.web.UsersFunctions;

public class NewUserEmpleadoFragment extends Fragment{
	View rootView;
	TimePicker inHour;
	TimePicker outHour;
	Button toBackAction;
	Button addAction;
	Bundle bundle;
	UsersFunctions userFunctions = new UsersFunctions();
	User userPrincipalInfo;
	EmpleadoHorario mEmpleadoHorario = new EmpleadoHorario(); 
	JSONObject jsonRegisterEmploye = new JSONObject();
	JSONObject json_user = null;
	JSONObject json;
	ProgressDialog pDialog;
	globalFunctions globalFunctions = new globalFunctions();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.new_user_empleado, container, false);
		inHour = (TimePicker)rootView.findViewById(R.id.timeIn);
		outHour = (TimePicker)rootView.findViewById(R.id.timeOut);
		addAction = (Button)rootView.findViewById(R.id.agregarAction);
		bundle = this.getArguments();


		addAction.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				userPrincipalInfo = bundle.getParcelable("userToAdd");
				new createUser().execute(userPrincipalInfo);
			}
		}); 

		return rootView;
	}


	private class createUser extends AsyncTask<Object, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(Object... params) {
			User userToInsert = (User) params[0];
			return insertUser(userToInsert);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
		}

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(rootView.getContext());
			pDialog.setMessage("Agregando usuario...");
			pDialog.setCancelable(false);
			pDialog.show();
		}

		public Boolean insertUser(User userToInsert){
			json = userFunctions.registerUser(userToInsert);
			try {
				if(json.getInt("error") == 0){
					json_user = json.getJSONObject("user");

					String minutesIn = "";
					if(inHour.getCurrentMinute() >=0 && inHour.getCurrentMinute() < 10){
						minutesIn = "0"+String.valueOf(inHour.getCurrentMinute());
					}else{
						minutesIn = String.valueOf(inHour.getCurrentMinute());
					}
					String hourIn = "";
					if(inHour.getCurrentHour() >=0 && inHour.getCurrentHour() < 10){
						hourIn = "0"+String.valueOf(inHour.getCurrentHour());
					}else{
						hourIn = String.valueOf(inHour.getCurrentHour());
					}


					String minutesOut = "";
					if(outHour.getCurrentMinute() >=0 && outHour.getCurrentMinute() < 10){
						minutesOut = "0"+String.valueOf(outHour.getCurrentMinute());
					}else{
						minutesOut = String.valueOf(outHour.getCurrentMinute());
					}
					String hourOut = "";
					if(outHour.getCurrentHour() >=0 && outHour.getCurrentHour() < 10){
						hourOut = "0"+String.valueOf(outHour.getCurrentHour());
					}else{
						hourOut = String.valueOf(outHour.getCurrentHour());
					}

					mEmpleadoHorario.setId(json_user.getInt("id"));
					mEmpleadoHorario.setInicio(hourIn+":"+minutesIn);
					mEmpleadoHorario.setH_final(hourOut+":"+minutesOut);

					JSONObject json_employe = userFunctions.registerEmploye(mEmpleadoHorario);

					//Delete bundle to save memory
					bundle.remove("userToAdd");
					bundle.clear();

					return (json_employe.getInt("error")==0)?true:false;
				}else{
					return false;
				}



			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (pDialog.isShowing()){
				pDialog.dismiss();
			}
			if(result){
				Toast.makeText(rootView.getContext(), "El usuario se ha agregado con exito", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(rootView.getContext(), "Ocurrio un error al agregar el usuario", Toast.LENGTH_SHORT).show();
			}
			globalFunctions.closeKeyboard(rootView.getContext(), rootView.getWindowToken());
			Fragment fragment = new HomeFragment();
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
		}
	}


	//Hide the keyboard when the Fragmenet is created
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
	}

}
